package com.kangyi.user.controller;

import com.kangyi.dto.FavoriteDTO;
import com.kangyi.result.Result;
import com.kangyi.user.service.NursingHomeFavoriteService;
import com.kangyi.utils.AuthUtil;
import com.kangyi.vo.NursingHomeFavoriteVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Blank
 * @version 1.0
 */
@RestController
@RequestMapping("/user/favorite")
@Api(tags = "收藏相关接口")
@Slf4j
public class NursingHomeFavoriteController {

    @Autowired
    private NursingHomeFavoriteService nursingHomeFavoriteService;

    @GetMapping("/list/{userId}")
    @ApiOperation("查询用户下收藏的养老院")
    @Cacheable(cacheNames = "favorite_",key = "'userList_'+#userId")
    public Result<List<NursingHomeFavoriteVO>> listFavorite(@PathVariable Integer userId){
        log.info("查询用户下收藏的养老院：{}",userId);
        try {
            AuthUtil.validateUserPermission(userId);

            List<NursingHomeFavoriteVO> nursingHomeFavoriteVOList = nursingHomeFavoriteService.listFavorite(userId);
            return Result.success(nursingHomeFavoriteVOList,"查询成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/add")
    @ApiOperation("收藏养老院")
    @CacheEvict(cacheNames = "favorite_",allEntries = true)
    public Result addFavorite(FavoriteDTO favoriteDTO){
        log.info("收藏养老院");
        try {
            AuthUtil.validateUserPermission(favoriteDTO.getUserId());

            nursingHomeFavoriteService.addFavorite(favoriteDTO);
            return Result.success("收藏成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/cancel")
    @ApiOperation("取消收藏养老院")
    @CacheEvict(cacheNames = "favorite_",allEntries = true)
    public Result cancelFavorite(FavoriteDTO favoriteDTO){
        log.info("取消收藏养老院:{}",favoriteDTO);
        try {
            nursingHomeFavoriteService.cancelFavorite(favoriteDTO);
            return Result.success("取消成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }


    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除收藏养老院")
    @CacheEvict(cacheNames = "favorite_",allEntries = true)
    public Result deleteFavorite(@PathVariable Integer id){
        log.info("删除收藏养老院:{}",id);
        try {
            nursingHomeFavoriteService.deleteFavorite(id);
            return Result.success("删除成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
